package org.ponly.cta4j.service.store.redis;

import java.io.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 一个简单的序列化工具.
 *
 * @author vacoor
 * @since 1.0
 */
abstract class SerializeUtils {
    /**
     * logger.
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(SerializeUtils.class);

    /**
     * 反序列化.
     *
     * @param bytes 对象字节数组.
     * @return 反序列化后的对象.
     */
    public static Object deserialize(final byte[] bytes) {
        Object result = null;

        if (isEmpty(bytes)) {
            return null;
        }

        try {
            final ByteArrayInputStream byteStream = new ByteArrayInputStream(bytes);
            try {
                final ObjectInputStream objectInputStream = new ObjectInputStream(byteStream);
                try {
                    result = objectInputStream.readObject();
                } catch (final ClassNotFoundException ex) {
                    throw new Exception("Failed to deserialize object type", ex);
                }
            } catch (final Throwable ex) {
                throw new Exception("Failed to deserialize", ex);
            }
        } catch (final Exception e) {
            LOGGER.error("Failed to deserialize", e);
        }
        return result;
    }

    /**
     * @param data 数组
     * @return 是否空白
     */
    public static boolean isEmpty(final byte[] data) {
        return (data == null || data.length == 0);
    }

    /**
     * 序列化对象为字节数组.
     *
     * @param object 要序列化的对象.
     * @return 对象的字节数组
     */
    public static byte[] serialize(final Object object) {
        byte[] result = null;

        if (object == null) {
            return new byte[0];
        }

        try {
            final ByteArrayOutputStream byteStream = new ByteArrayOutputStream(128);
            try {
                if (!(object instanceof Serializable)) {
                    throw new IllegalArgumentException(SerializeUtils.class.getSimpleName() + " requires a Serializable payload "
                            + "but received an object of type [" + object.getClass().getName() + ']');
                }
                final ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteStream);
                objectOutputStream.writeObject(object);
                objectOutputStream.flush();
                result = byteStream.toByteArray();
            } catch (final Throwable ex) {
                throw new Exception("Failed to serialize", ex);
            }
        } catch (final Exception ex) {
            LOGGER.error("Failed to serialize", ex);
        }
        return result;
    }
}
